/*
 * Copyright 2023-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package net.yun789.javasipweb;


import net.yun789.javasipweb.config.TcpDecoderHandler;
import net.yun789.javasipweb.config.UdpDecoderHandler;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Flux;
import reactor.netty.tcp.TcpServer;
import reactor.netty.udp.UdpServer;

import java.time.Duration;

@SpringBootApplication
public class JavaSipWebApplication {

    public static void main(String[] args) {
//        new SipPhone().init();
        SpringApplication.run(JavaSipWebApplication.class, args);
    }

    @Bean
    CommandLineRunner serverRunner(UdpDecoderHandler udpDecoderHandler, TcpDecoderHandler tcpDecoderHandler) {
        return strings -> {
            createUdpServer(udpDecoderHandler);
            createTcpServer(tcpDecoderHandler);
        };


    }
    /**
     * 创建UDP Server
     * @param udpDecoderHandler： 解析UDP Client上报数据handler
     */
    private void createUdpServer(UdpDecoderHandler udpDecoderHandler) {
        UdpServer udpServer = UdpServer.create()
                .handle((in, out) -> {
                    in.receive()
                            .asByteArray()
                            .subscribe();
                    return Flux.never();
                });
        udpServer
                .port(8060)
                .doOnBound(conn -> conn.addHandlerLast("decoder", udpDecoderHandler)) //可以添加多个handler
                .bindNow(Duration.ofSeconds(30));
        udpServer.port(8061);
    }
    /**
     * 创建TCP Server
     * @param tcpDecoderHandler： 解析TCP Client上报数据的handler
     */
    private void createTcpServer(TcpDecoderHandler tcpDecoderHandler) {
        TcpServer.create()
                .handle((in,out) -> {
                    in.receive()
                            .asByteArray()
                            .subscribe();
                    return Flux.never();
                })
                .doOnConnection(conn ->
                        conn.addHandler(tcpDecoderHandler)) //实例只写了如何添加handler,可添加delimiter，tcp生命周期，decoder，encoder等handler
                .port(9999)
                .bindNow();
    }

}
